package cn.bugstack.infrastructure.adapter.port;

import cn.bugstack.domain.order.adapter.port.IProductPort;
import cn.bugstack.domain.order.model.entity.MarketPayDiscountEntity;
import cn.bugstack.domain.order.model.entity.ProductEntity;
import cn.bugstack.infrastructure.gateway.IGroupBuyMarketService;
import cn.bugstack.infrastructure.gateway.ProductRPC;
import cn.bugstack.infrastructure.gateway.dto.*;
import cn.bugstack.infrastructure.gateway.response.Response;
import cn.bugstack.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class ProductPort implements IProductPort {
    @Value("${app.config.group-buy-market.source}")
    private String source;
    @Value("${app.config.group-buy-market.chanel}")
    private String chanel;
    @Value("${app.config.group-buy-market.notify-url}")
    private String notifyUrl;
    private final ProductRPC productRPC;

    private final IGroupBuyMarketService groupBuyMarketService;

    public ProductPort(ProductRPC productRPC, IGroupBuyMarketService groupBuyMarketService) {
        this.productRPC = productRPC;
        this.groupBuyMarketService = groupBuyMarketService;
    }

    @Override
    public ProductEntity queryProductByProductId(String productId) {
        ProductDTO productDTO = productRPC.queryProductByProductId(productId);
        return ProductEntity.builder().productId(productDTO.getProductId()).productName(productDTO.getProductName()).productDesc(productDTO.getProductDesc()).price(productDTO.getPrice()).build();
    }

    @Override
    public MarketPayDiscountEntity lockMarketPayOrder(String userId, String teamId, Long activityId, String productId, String orderId) {
        LockMarketPayOrderRequestDTO lockMarketPayOrderRequestDTO = new LockMarketPayOrderRequestDTO();
        // 请求参数
        lockMarketPayOrderRequestDTO.setUserId(userId);
        lockMarketPayOrderRequestDTO.setActivityId(activityId);
        lockMarketPayOrderRequestDTO.setTeamId(teamId);
        lockMarketPayOrderRequestDTO.setGoodsId(productId);
        lockMarketPayOrderRequestDTO.setOutTradeNo(orderId);
        lockMarketPayOrderRequestDTO.setChannel(chanel);
        lockMarketPayOrderRequestDTO.setSource(source);
//        lockMarketPayOrderRequestDTO.setNotifyUrl(notifyUrl);
        lockMarketPayOrderRequestDTO.setNotifyMQ();

        try {
            // 营销锁单
            Call<Response<LockMarketPayOrderResponseDTO>> call = groupBuyMarketService.lockMarketPayOrder(lockMarketPayOrderRequestDTO);
            // 获取结果
            Response<LockMarketPayOrderResponseDTO> response = call.execute().body();
            log.info("营销锁单{} requestDTO:{} responseDTO:{}", userId, JSON.toJSONString(lockMarketPayOrderRequestDTO), JSON.toJSONString(lockMarketPayOrderRequestDTO));
            if (response == null) {
                return null;
            }
            // 异常判断 “0000”为自定义的响应码锁单的返回值会包含这个东西
            if (!response.getCode().equals("0000")) {
                throw new AppException(response.getCode(), response.getInfo());
            }
            LockMarketPayOrderResponseDTO responseDTO = response.getData();
            // 获取拼团优惠
            MarketPayDiscountEntity marketPayDiscountEntity = MarketPayDiscountEntity.builder().originalPrice(responseDTO.getOriginalPrice()).deductionPrice(responseDTO.getDeductionPrice()).payPrice(responseDTO.getPayPrice()).build();
            return marketPayDiscountEntity;
        } catch (IOException e) {
            log.error("营销锁单失败{}", userId, e);
            return null;
        }
    }

    @Override
    public void settlementMarketPayOrder(String userId, String orderId, Date payTime) {
        // 请求参数
        SettlementMarketPayOrderRequestDTO settlementMarketPayOrderRequestDTO = new SettlementMarketPayOrderRequestDTO();
        settlementMarketPayOrderRequestDTO.setChannel(chanel);
        settlementMarketPayOrderRequestDTO.setSource(source);
        settlementMarketPayOrderRequestDTO.setUserId(userId);
        settlementMarketPayOrderRequestDTO.setOutTradeTime(payTime);
        settlementMarketPayOrderRequestDTO.setOutTradeNo(orderId);

        try {
            // 营销结算
            Call<Response<SettlementMarketPayOrderResponseDTO>> call = groupBuyMarketService.settlementMarketPayOrder(settlementMarketPayOrderRequestDTO);
            // 获取结果
            Response<SettlementMarketPayOrderResponseDTO> response = call.execute().body();
            log.info("营销结算{} requestDTO:{} responseDTO:{}", userId, JSON.toJSONString(settlementMarketPayOrderRequestDTO), JSON.toJSONString(settlementMarketPayOrderRequestDTO));
            if (response == null) {
                return;
            }
            // 异常判断
            if (!response.getCode().equals("0000")) {
                throw new AppException(response.getCode(), response.getInfo());
            }
        } catch (Exception e) {
            log.error("营销结算失败{}", userId, e);
        }


    }

    @Override
    public void refundMarketPayOrder(String userId, String orderId) {
        RefundMarketPayOrderRequestDTO requestDTO = new RefundMarketPayOrderRequestDTO();
        requestDTO.setSource(source);
        requestDTO.setChannel(chanel);
        requestDTO.setUserId(userId);
        requestDTO.setOutTradeNo(orderId);

        try {
            Call<Response<RefundMarketPayOrderResponseDTO>> call = groupBuyMarketService.refundMarketPayOrder(requestDTO);

            // 获取结果
            Response<RefundMarketPayOrderResponseDTO> response = call.execute().body();
            log.info("营销退单{} requestDTO:{} responseDTO:{}", userId, JSON.toJSONString(requestDTO), JSON.toJSONString(response));
            if (null == response) return;

            // 异常判断
            if (!"0000".equals(response.getCode())) {
                throw new AppException(response.getCode(), response.getInfo());
            }

        } catch (Exception e) {
            log.error("营销退单失败{}", userId, e);
        }
    }
}
